﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace StudentManagement.Util.ValidationRules
{
    public class ValidationUtil
    {
        /// <summary>
        /// 检查控件中是否有错误
        /// </summary>
        /// <param name="elements">需要检查的按钮</param>
        /// <returns>是否全部校验通过</returns>
        public static bool CheckIsError(params DependencyObject[] elements)
        {
            bool isError = false;
            foreach (var element in elements)
            {
                bool isValid = IsValid(element);
                if (!isError && !isValid)
                {
                    isError = true;
                }
            }
            return isError;
        }

        /// <summary>
        /// 验证控件中的值是否有效。
        /// （来自Chris Sell＆Ian Griffiths的《 Programming WPF》一书）验证了依赖对象及其子对象上的所有绑定规则。
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>

        public static bool IsValid(DependencyObject parent)
        {
            // Validate all the bindings on the parent

            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;

                if (BindingOperations.IsDataBound(parent, entry.Property))
                {

                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);

                    foreach (ValidationRule rule in binding.ValidationRules)
                    {

                        ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);

                        if (!result.IsValid)
                        {

                            BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);

                            Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));

                            return false;

                        }

                    }

                }

            }

            // Validate all the bindings on the children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                if (!IsValid(child))
                {
                    return false;
                }
            }

            return true;

        }
    }
}
